package org.example.im.server.handler.impl.biz;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.example.im.bean.protocol.CommandType;
import org.example.im.bean.protocol.request.Send2UserRequestPacket;
import org.example.im.bean.protocol.response.Send2UserResponsePacket;
import org.example.im.bean.session.Session;
import org.example.im.common.util.SessionUtil;
import org.example.im.server.handler.ServerHandler;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author dingrui
 * @since 2022/2/11
 * @description 发消息
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class Send2UserHandler extends SimpleChannelInboundHandler<Send2UserRequestPacket> implements ServerHandler {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Send2UserRequestPacket request) throws Exception {
        // 发送方
        Session session = SessionUtil.getSession(ctx.channel());
        // 接收方
        String toUserId = request.getToUserId();
        Channel toChannel = SessionUtil.getChannel(toUserId);
        // 接收方离线
        if (Objects.isNull(toChannel) || !SessionUtil.hasLogin(toChannel)) return;
        // 消息
        String fromUserId = session.getUserId(); // 发送方
        String fromUserName = session.getUserName(); // 发送方
        String msg = request.getMessage(); // 消息内容
        Send2UserResponsePacket response = Send2UserResponsePacket.builder().fromUserId(fromUserId).fromUserName(fromUserName).message(msg).build();
        // 发送
        toChannel.writeAndFlush(response);
    }

    @Override
    public CommandType genType() {
        return CommandType.SEND_2_USER_REQUEST;
    }
}
